from datetime import datetime

from flask import request, jsonify

from app import db

from ..base import base

from ..models.AuthInfo import AuthInfo


# 查询所有授权信息
@base.route('/auth_check', methods=['GET'])
def auth_check():
    # 获取客户端的IP
    client_ip = request.remote_addr

    # 从反向代理中获取真实客户端IP（如果有）
    if request.headers.getlist("X-Forwarded-For"):
        client_ip = request.headers.getlist("X-Forwarded-For")[0]

    # 获取查询状态参数
    status = request.args.get('status', 1)  # 默认查询状态为1，代表有效授权

    # 查询授权信息，基于IP和状态
    auth_info = AuthInfo.query.filter_by(bind_ip=client_ip, status=status).first()

    # 如果查询为空，返回失败
    if not auth_info:
        return jsonify({"message": "授权失败，未找到有效的授权信息"}), 400

    # 检查是否过期
    current_time = datetime.utcnow()
    if auth_info.end_time and auth_info.end_time < current_time:
        return jsonify({"message": "授权失败，授权已过期"}), 400

    # 授权成功
    return jsonify({"message": "授权成功", "auth_info": auth_info.to_json()})


# 查询所有授权信息
@base.route('/auth_info_list', methods=['GET'])
def get_auth_info_list():
    print(f"get_auth_info_list|查询语句")
    # 获取请求参数
    filters = {}
    if request.args.get('id'):
        filters['id'] = request.args.get('id')
    if request.args.get('auth_code'):
        filters['auth_code'] = request.args.get('auth_code')
    if request.args.get('bind_ip'):
        filters['bind_ip'] = request.args.get('bind_ip')
    if request.args.get('status'):
        filters['status'] = request.args.get('status')
    if request.args.get('auth_scope'):
        filters['auth_scope'] = request.args.get('auth_scope')

    # 使用动态过滤条件构建查询
    query = AuthInfo.query.filter_by(**filters)

    # 获取查询结果
    auth_infos = query.all()

    # 返回查询结果
    return jsonify([auth_info.to_json() for auth_info in auth_infos])


# 根据ID查询授权信息
@base.route('/auth_info/<int:id>', methods=['GET'])
def get_auth_info(id):
    auth_info = AuthInfo.query.get_or_404(id)
    return jsonify(auth_info.to_json())


# 新增授权信息
@base.route('/auth_info', methods=['POST'])
def create_auth_info():
    data = request.json
    new_auth_info = AuthInfo(
        auth_code=data.get('auth_code'),
        start_time=data.get('start_time'),
        end_time=data.get('end_time'),
        bind_ip=data.get('bind_ip'),
        status=data.get('status'),
        page_download_count=data.get('page_download_count'),
        auth_scope=data.get('auth_scope')
    )
    db.session.add(new_auth_info)
    db.session.commit()
    return jsonify(new_auth_info.to_json()), 201


@base.route('/auth_info/update_by_code', methods=['PUT'])
def update_auth_info_by_code():
    # 从请求中获取授权码
    auth_code = request.json.get('auth_code')
    if not auth_code:
        return jsonify({"message": "授权码不存在"}), 400

    # 根据 auth_code 查找记录
    auth_info = AuthInfo.query.filter_by(auth_code=auth_code).first()

    # 如果找不到记录，返回 404
    if not auth_info:
        return jsonify({"message": "授权码不存在"}), 400

    # 获取请求中的数据并更新记录
    data = request.json
    auth_info.bind_ip = data.get('bind_ip', auth_info.bind_ip)
    auth_info.status = data.get('status', auth_info.status)

    # 提交更改
    db.session.commit()

    # 更新其他绑定该授权码的 IP 状态为 -1
    AuthInfo.query.filter(AuthInfo.auth_code == auth_code, AuthInfo.bind_ip != auth_info.bind_ip).update({'status': -1})
    db.session.commit()

    # 返回更新后的记录
    return jsonify(auth_info.to_json())


# 更新授权信息
@base.route('/auth_info/<int:id>', methods=['PUT'])
def update_auth_info(id):
    auth_info = AuthInfo.query.get_or_404(id)
    data = request.json

    auth_info.auth_code = data.get('auth_code', auth_info.auth_code)
    auth_info.start_time = data.get('start_time', auth_info.start_time)
    auth_info.end_time = data.get('end_time', auth_info.end_time)
    auth_info.bind_ip = data.get('bind_ip', auth_info.bind_ip)
    auth_info.status = data.get('status', auth_info.status)
    auth_info.page_download_count = data.get('page_download_count', auth_info.page_download_count)
    auth_info.auth_scope = data.get('auth_scope', auth_info.auth_scope)

    db.session.commit()
    return jsonify(auth_info.to_json())


# 删除授权信息
@base.route('/auth_info/<int:id>', methods=['DELETE'])
def delete_auth_info(id):
    auth_info = AuthInfo.query.get_or_404(id)
    db.session.delete(auth_info)
    db.session.commit()
    return jsonify({'message': f'AuthInfo with id {id} has been deleted.'}), 200
